package pdfsetter.core.schema.selectors;

import java.util.Iterator;

import pdfsetter.core.schema.advanced.FilePageSelection;
import pdfsetter.core.schema.advanced.FilePageSelector;
import pdfsetter.core.util.RandomAccessIterableIterator;

/**
 * This is very simple selector. We take all pages but in reverse order, so thanks to it we can go through the file backwards.
 * 
 * @author Andrzej Dorobisz
 */
public class ReversingPageSelector implements FilePageSelector {
    @Override
    public FilePageSelection selectPages(int fileSize) {
        return new ReversedPageSelection(fileSize);
    }

    private class ReversedPageSelection implements FilePageSelection {
        private final int size;

        public ReversedPageSelection(int fileSize) {
            this.size = fileSize;
        }

        @Override
        public Integer get(int index) {
            if (index >= size || index < 0)
                throw new IndexOutOfBoundsException();
            return size - 1 - index;
        }

        @Override
        public int size() {
            return size;
        }

        @Override
        public Iterator<Integer> iterator() {
            return new RandomAccessIterableIterator<Integer>(this);
        }

    }
}
